<template>
  <div class="trip-container">
    <a-card class="trip-card" :bordered="false">
      <!-- 顶部标题和操作区 -->
      <div class="header-section">
        <h2 class="page-title">出车管理</h2>
        <div class="table-operations">
          <a-row :gutter="16" align="middle">
            <a-col :span="8">
              <a-input-search
                v-model:value="search"
                placeholder="搜索出车记录..."
                @search="fetchTripList"
                enter-button
                size="large"
                class="search-input"
              />
            </a-col>
            <a-col :span="16" style="text-align: right">
              <a-button type="primary" size="large" @click="showAddModal" class="add-button">
                <car-outlined />
                新增出车记录
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 出车记录表格 -->
      <a-table
        :columns="columns"
        :data-source="tripList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        class="custom-table"
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
      >
        <!-- 自定义列显示 -->
        <template v-slot:bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'vehicleId'">
            <div class="vehicle-info">
              <car-outlined class="info-icon" />
              <span>{{ getVehicleName(record.vehicleId) }}</span>
            </div>
          </template>
          <template v-if="column.dataIndex === 'driverId'">
            <a-tag color="blue">
              <user-outlined /> {{ getDriverName(record.driverId) }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'userId'">
            <a-tag color="blue">
              <user-outlined /> {{ getUserName(record.userId) }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'usageTime'">
            <span class="time-text">
              {{ record.usageTime ? dayjs(record.usageTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'returnTime'">
            <span class="time-text">
              {{ record.returnTime ? dayjs(record.returnTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'tripReason'">
            <a-tooltip :title="record.tripReason">
              <div class="reason-text">{{ record.tripReason }}</div>
            </a-tooltip>
          </template>
          <template v-if="column.dataIndex === 'checkStatus'">
            <a-tag :color="record.checkStatus === 0 ? 'red' : 'green'">
              {{ record.checkStatus === 0 ? '未审核' : '已审核' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="showEditModal(record)" class="edit-button">
                <edit-outlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这条出车记录吗？"
                @confirm="handleDelete(record.tripId)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button type="link" danger class="delete-button">
                  <delete-outlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 添加/编辑出车记录模态框 -->
      <a-modal
        :title="modalTitle"
        :open="modalVisible"
        @ok="handleModalOk"
        @cancel="handleModalCancel"
        class="trip-modal"
        :maskClosable="false"
        :width="500"
      >
        <a-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="用车时间" name="usageTime">
            <a-date-picker
              v-model:value="formData.usageTime"
              placeholder="请选择用车时间"
              :locale="zhCN"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
              class="custom-date-picker"
            />
          </a-form-item>
          <a-form-item label="车牌号" name="vehicleId">
            <a-select
              v-model:value="formData.vehicleId"
              placeholder="请选择车牌号"
              @change="getDriver"
              show-search
              :filter-option="filterVehicleOption"
              class="custom-select"
            >
              <a-select-option
                v-for="v in getNoUseVehicleList"
                :key="v.vehicleId"
                :value="v.vehicleId"
              >
                {{ v.licensePlate }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="驾驶员" name="driverId">
            <a-input
              v-model:value="formData.driverName"
              disabled
              class="custom-input"
            />
          </a-form-item>
          <a-form-item label="申请人" name="userId">
            <a-select
                v-model:value="formData.userId"
                placeholder="请选择申请人"
                show-search
                class="custom-select"
            >
              <a-select-option
                  v-for="v in getUserList"
                  :key="v.userId"
                  :value="v.userId"
              >
                {{ v.username }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="出车事由" name="tripReason">
            <a-textarea
              v-model:value="formData.tripReason"
              :rows="4"
              placeholder="请输入出车事由"
              class="custom-textarea"
            />
          </a-form-item>
          <a-form-item label="归来时间" name="returnTime">
            <a-date-picker
              v-model:value="formData.returnTime"
              placeholder="请选择归来时间"
              :locale="zhCN"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
              class="custom-date-picker"
            />
          </a-form-item>
          <a-form-item label="审核状态" name="checkStatus">
            <a-radio-group v-model:value="formData.checkStatus">
              <a-radio :value="0">未审核</a-radio>
              <a-radio :value="1">已审核</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, CarOutlined, UserOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { list,add,del,update } from '@/api/trip'
import { getDataList } from '@/api/data'
import { getDriverByVehicle,getNoUseVehicleInfo  } from '@/api/vehicle'
import dayjs from 'dayjs'
import zhCN from 'ant-design-vue/es/date-picker/locale/zh_CN'
// 表格列定义
const columns = [
  {
    title: '用车时间',
    dataIndex: 'usageTime',
    key: 'usageTime',
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '--'
  },
  {
    title: '车牌号',
    dataIndex: 'vehicleId',
    key: 'vehicleId',
  },
  {
    title: '驾驶人',
    dataIndex: 'driverId',
    key: 'driverId',

  },
  {
    title:'申请人',
    dataIndex: 'userId',
    key:'userId'
  },
  {
    title: '出车事由',
    dataIndex: 'tripReason',
    key: 'tripReason',
  },
  {
    title: '归来时间',
    dataIndex: 'returnTime',
    key: 'returnTime',
     customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '--'
  },
  {
    title: '审核状态',
    dataIndex: 'checkStatus',
    key:'checkStatus'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]

// 数据相关
const loading = ref(false)
const tripList=ref([])
//所有车辆
const getVehicleList=ref([])
//未使用车辆
const getNoUseVehicleList=ref([])
const getDriverList=ref([])
const getUserList=ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
})
const search=ref('')
// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加出车信息')
const formRef = ref(null)
const formData = ref({
  usageTime: null,
  vehicleId: '',
  driverId: '',
  driverName: '',
  tripReason: '',
  returnTime: null,
  checkStatus:''
})

// 表单验证规则
const rules = {
  usageTime: [
    { required: true, message: '请选择用车时间', trigger: 'change' }
  ],
  tripReason: [
    { required: true, message: '请输入出车事由', trigger: 'blur' },
  ],
  driverId: [
    { required: true, message: '请选择驾驶员', trigger: 'change' }
  ],
  vehicleId:[
  { required: true, message: '请选择驾驶员', trigger: 'change' }
  ],
  returnTime: [
    { required: true, message: '请选择归来时间', trigger: 'change' }
  ],
}

// 获取驾驶员名称
const getDriverName = (driverId) => {
  const driver = getDriverList.value.find(dr => dr.driverId === driverId)
  return driver ? driver.name : '-'
}
//获取车牌号
const getVehicleName = (vehicleId) => {
  const vehicle = getVehicleList.value.find(v => v.vehicleId === vehicleId)
  return vehicle ? vehicle.licensePlate : '-'
}

const getUserName=(userId)=>{
  const user = getUserList.value.find(u => u.userId === userId)
  return user ? user.username : '-'
}
// 过滤车牌号
const filterVehicleOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 页面加载时获取数据
onMounted(() => {
  DataList()
  fetchTripList()
})
const DataList=async()=>{
      const res =await getDataList();
      const res1=await getNoUseVehicleInfo();
      console.log(res)
      console.log(res1)
      if(res.code===200){
         getVehicleList.value=res.data.vehicleInfoList
          getDriverList.value=res.data.driverInfoList
          getUserList.value=res.data.userInfoList
      }
      if(res1.code===200){
          getNoUseVehicleList.value=res1.data
      }
}

const getDriver = async (vehicleId) => {
  try {
    const res = await getDriverByVehicle(vehicleId)
    if (res.code === 200) {
      // 只存储驾驶员ID，而不是名字
      console.log(res)
      formData.value.driverId = res.data.driverId
      // 在输入框中显示驾驶员名字
      const driver = getDriverList.value.find(d => d.driverId === res.data.driverId)
      formData.value.driverName = driver ? driver.name : '' // 用于显示
    } else {
      formData.value.driverId = ''
      formData.value.driverName = ''
      message.warning('该车辆暂无指定驾驶员')
    }
  } catch (error) {
    console.error('获取驾驶员信息失败:', error)
    message.error('获取驾驶员信息失败')
    formData.value.driverId = ''
    formData.value.driverName = ''
  }
}

// 获取出车信息列表
const fetchTripList = async () => {
  loading.value = true
  try {
    const res = await list({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      search: search.value
    })
    console.log(res)
    tripList.value = res.data.records
    pagination.value.total = res.data.total
  } catch (error) {
    message.error('获取出车信息列表失败')
  } finally {
    loading.value = false
  }
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchDriverList()
}

// 显示添加模态框
const showAddModal = () => {
  modalTitle.value = '添加车辆'
  formData.value = {
      usageTime: null,
      vehicleId: '',
      driverId: '',
      tripReason: '',
      returnTime: null,
  }
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record) => {
  modalTitle.value = '编辑出车信息'
  formData.value = {
    ...record,
    usageTime: record.usageTime ? dayjs(record.usageTime) : null,
    returnTime: record.returnTime ? dayjs(record.returnTime) : null,
    driverName: getDriverName(record.driverId) // 设置驾驶员名字用于显示
  }
  modalVisible.value = true
}

// 处理模态框确认
const handleModalOk = () => {
  formRef.value?.validate().then(async () => {
    try {
      const submitData = {
        ...formData.value,
        usageTime: formData.value.usageTime ? formData.value.usageTime.format('YYYY-MM-DD HH:mm:ss') : null,
        returnTime: formData.value.returnTime ? formData.value.returnTime.format('YYYY-MM-DD HH:mm:ss') : null,
      }
      // 删除不需要提交的显示字段
      delete submitData.driverName

      const res = formData.value.tripId
        ? await update(submitData)
        : await add(submitData)
      console.log(res)
      if(res.code === 200) {
        message.success(`${modalTitle.value}成功`)
        modalVisible.value = false
        fetchTripList()
      }
    } catch (error) {
      message.error(`${modalTitle.value}失败`)
    }
  })
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 处理删除车辆
const handleDelete = async (tripId) => {
  try {
    const res = await del(tripId)
    if(res.code === 200) {
      message.success('删除成功')
      fetchTripList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}
// 页面加载时获取列表数据
onMounted(() => {
  fetchTripList()
  DataList()
})
</script>

<style scoped>
.trip-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.trip-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-section {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #1f1f1f;
  margin-bottom: 24px;
  font-weight: 500;
}

.search-input {
  width: 100%;
  :deep(.ant-input) {
    border-radius: 4px;
  }
}

.add-button {
  border-radius: 4px;
  height: 40px;
  font-weight: 500;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
}

.custom-table {
  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 500;
  }

  :deep(.table-striped) {
    background-color: #fafafa;
  }
}

.vehicle-info {
  display: flex;
  align-items: center;
  gap: 8px;

  .info-icon {
    color: #1890ff;
    background: #e6f7ff;
    padding: 4px;
    border-radius: 50%;
  }
}

.time-text {
  color: #666;
  font-family: 'Roboto Mono', monospace;
}

.reason-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.edit-button {
  color: #1890ff;
}

.delete-button {
  color: #ff4d4f;
}

.trip-modal {
  :deep(.ant-modal-header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }

  :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
}

.custom-input,
.custom-select,
.custom-date-picker,
.custom-textarea {
  width: 100%;
  :deep(.ant-input),
  :deep(.ant-select-selector),
  :deep(.ant-picker),
  :deep(.ant-input-textarea) {
    border-radius: 4px;
  }
}

/* 添加动画效果 */
.add-button,
.edit-button,
.delete-button {
  transition: all 0.3s;

  &:hover {
    transform: translateY(-1px);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .trip-container {
    padding: 12px;
  }

  .page-title {
    font-size: 20px;
  }

  .header-section {
    margin-bottom: 16px;
  }

  .search-input,
  .add-button {
    margin-bottom: 12px;
  }

  .reason-text {
    max-width: 120px;
  }
}
</style>
